package org.xiaojl.modules.task.controller;

import java.util.Date;
import java.util.List;

import javax.validation.Valid;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.xiaojl.common.Constants;
import org.xiaojl.common.SessionUser;
import org.xiaojl.common.base.BaseController;
import org.xiaojl.config.easyui.PageBean;
import org.xiaojl.config.easyui.PageParam;
import org.xiaojl.config.quartz.service.TaskJobManageService;
import org.xiaojl.modules.task.entity.TaskJob;
import org.xiaojl.modules.task.service.TaskJobService;
import org.xiaojl.utils.ToolUtil;
import org.xiaojl.utils.WebUtil;

import com.baomidou.mybatisplus.mapper.EntityWrapper;

/**
 * <p>
 * 定时任务表 前端控制器
 * </p>
 *
 * @author xiaojl
 * @since 2017-09-19
 */
@Controller
@RequestMapping("/task/taskJob")
public class TaskJobController extends BaseController {
	private static final Logger log = LoggerFactory.getLogger(TaskJobController.class);
	private static final String basePagePath = "task/taskJob/";
	
	@Autowired
	private TaskJobService taskJobService;
	@Autowired
	private TaskJobManageService taskJobManageService;
	
	/**
	 * 暂停
	 */
	@RequiresPermissions("task/taskJob/pause")
	@RequestMapping("/pause")
	public @ResponseBody Object pause(Long id) {
		try {
			TaskJob entity = taskJobService.selectById(id);
			if (ToolUtil.isEmpty(entity)) {
				return operateError("无法获取想要的数据");
			}
			
			entity.setJobStatus(Constants.JOB_STATUS_NOT_RUNNING);
			entity.setUpdateTime(new Date());
			taskJobService.updateById(entity);
			
			taskJobManageService.pauseTaskJob(entity);
			
			return operateSuccess("任务暂停成功！");
		} catch (Exception e) {
			log.error("暂停出现异常:id="+id, e);
			return operateError("任务暂停失败！");
		}
	}
	
	/**
	 * 恢复
	 */
	@RequiresPermissions("task/taskJob/resume")
	@RequestMapping("/resume")
	public @ResponseBody Object resume(Long id) {
		try {
			TaskJob entity = taskJobService.selectById(id);
			if (ToolUtil.isEmpty(entity)) {
				return operateError("无法获取想要的数据");
			}
			
			entity.setJobStatus(Constants.JOB_STATUS_RUNNING);
			entity.setUpdateTime(new Date());
			taskJobService.updateById(entity);
			
			taskJobManageService.resumeTaskJob(entity);
			
			return operateSuccess("任务启动成功！");
		} catch (Exception e) {
			log.error("启动任务出现异常:id="+id, e);
			return operateError("任务启动失败");
		}
	}
	
	/**
	 * 立即执行任务
	 */
	@RequiresPermissions("task/taskJob/run")
	@RequestMapping("/run")
	public @ResponseBody Object run(Long id) {
		try {
			TaskJob entity = taskJobService.selectById(id);
			if (ToolUtil.isEmpty(entity)) {
				return operateError("无法获取想要的数据");
			}
			
			taskJobManageService.runTaskJobNow(entity);
			
			return operateSuccess("任务立即执行成功！");
		} catch (Exception e) {
			log.error("任务立即执行出现异常:id="+id, e);
			return operateError("任务立即执行失败！");
		}
	}
	
	/**
	 * 进入列表页面
	 */
	@RequiresPermissions("task/taskJob/manager")
	@RequestMapping("/manager")
	public String manager(Model model){
		SessionUser su = WebUtil.getSessionUser();
		model.addAttribute("sessionUser", su);
		
		return basePagePath+"list";
	}
	
	/**
	 * 查询列表数据(分页)
	 */
	@RequiresPermissions("task/taskJob/manager")
	@RequestMapping("/dataGrid")
	public @ResponseBody Object dataGrid(PageParam pageParam, TaskJob entity){
		PageBean<TaskJob> pageBean = this.selectListPage(pageParam, entity, taskJobService);
		return pageBean;
	}
	
	/**
	 * 转到添加页面 
	 */
	@RequiresPermissions("task/taskJob/add")
	@RequestMapping("/addPage")
	public String addPage(){
		return basePagePath+"add";
	}
	
	/**
	 * 保存 .
	 */
	@RequiresPermissions("task/taskJob/add")
	@RequestMapping("/add")
	public @ResponseBody Object add(@Valid TaskJob entity, BindingResult result) {
		try {
			if(result.hasErrors()){
				return operateError(result.getAllErrors().get(0).getDefaultMessage());
			}
			
			/** 数据唯一性校验 */
			List<TaskJob> listByBeanId = taskJobService.selectList(new EntityWrapper<TaskJob>().eq("beanId",entity.getBeanId()));
			if (ToolUtil.isNotEmpty(listByBeanId)) {
				return operateError("BeanID【" + entity.getBeanId() + "】的定时任务已存在");
			}
			
			List<TaskJob> listByBeanClass = taskJobService.selectList(new EntityWrapper<TaskJob>().eq("beanClass",entity.getBeanClass()));
			if (ToolUtil.isNotEmpty(listByBeanClass)) {
				return operateError("BeanClass【" + entity.getBeanClass() + "】的定时任务已存在");
			}
			
			List<TaskJob> listByJobName = taskJobService.selectList(new EntityWrapper<TaskJob>().eq("jobName",entity.getJobName()));
			if (ToolUtil.isNotEmpty(listByJobName)) {
				return operateError("任务名称【" + entity.getJobName() + "】的定时任务已存在");
			}
			
			//插入数据库
			taskJobService.insert(entity);
			
			taskJobManageService.addTaskJob(entity);
			
			return operateSuccess("添加成功!");
		} catch (Exception e) {
			log.error("保存添加的数据，出现异常:", e);
			return operateError("添加失败!");
		}
	}
	
	/**
	 * 转到修改页面 .
	 */
	@RequiresPermissions("task/taskJob/edit")
	@RequestMapping("/editPage")
	public String editPage(Model model, Long id) {
		try {
			TaskJob entity = taskJobService.selectById(id);
			if (ToolUtil.isEmpty(entity)) {
				log.error("进入编辑页面时，获取想要修改的数据为空！id="+id);
			}

			model.addAttribute("entity",entity);
		} catch (Exception e) {
			log.error("进入编辑页面时，获取想要修改的数据出现异常:id="+id, e);
		}
		return  basePagePath+"edit" ;
	}
	
	/**
	 * 保存修改后的信息 .
	 */
	@RequiresPermissions("task/taskJob/edit")
	@RequestMapping("/edit")
	public @ResponseBody Object edit(@Valid TaskJob entity, BindingResult result) {
		try {
			if(result.hasErrors()){
				return operateError(result.getAllErrors().get(0).getDefaultMessage());
			}
			
			Long id = entity.getId();
			TaskJob oldObj = taskJobService.selectById(id);
			if (ToolUtil.isEmpty(oldObj)) {
				return operateError("保存修改的数据时，无法获取想要修改的数据，id="+id);
			}
			
			/** 数据唯一性校验逻辑*/
			if(!oldObj.getCron().equals(entity.getCron()) ||
					!oldObj.getJobName().equals(entity.getJobName()) ||
					!oldObj.getJobGroup().equals(entity.getJobGroup()) ){
				
				if(!oldObj.getJobName().equals(entity.getJobName())){
					List<TaskJob> listByJobName = taskJobService.selectList(new EntityWrapper<TaskJob>().eq("jobName",entity.getJobName()));
					if (ToolUtil.isNotEmpty(listByJobName)) {
						return operateError("任务名称【" + entity.getJobName() + "】的定时任务已存在");
					}
				}
				
				taskJobManageService.updateSchedule(entity);
			}
			
			//更新数据库
			taskJobService.updateById(entity);
			
			return operateSuccess("修改成功!");
		} catch (Exception e) {
			log.error("保存修改的数据时，出现异常:", e);
			return operateError("修改失败!");
		}
	}
	
	/**
	 * 删除
	 */
	@RequiresPermissions("task/taskJob/delete")
	@RequestMapping("/delete")
	public @ResponseBody Object delete(Long id) {
		try {
			TaskJob entity = taskJobService.selectById(id);
			if (ToolUtil.isEmpty(entity)) {
				return operateError("删除数据时，无法获取想要删除的数据，id="+id);
			}
			
			taskJobService.deleteById(id);
			
			taskJobManageService.resumeTaskJob(entity);
			
			return operateSuccess("删除成功!");
		} catch (Exception e) {
			log.error("删除数据时，出现异常:id="+id, e);
			return operateError("删除失败!");
		}
	}
	
}
